import { useEffect, useState } from 'react'
import examApi from '../api/index'
import { useLocation } from 'react-router-dom'
import './index.scss'
import { Button, Flex, Form, Input, Select, Switch, Tag } from 'antd'
import { MyDrawer } from '@/component/common/myDrawer'
import MyTable from '@/component/common/myTable'
import { MyDialog } from '@/component/common/myDialog'
import { UserArr } from '@/pages/user/interface'
import userApi from '@/pages/user/api'
import paperApi from '@/pages/examPaper/api'
import RegionSelect from '@/component/common/regionSelect/regionSelect'
import { USER_SEX } from '@/pages/user/config'
import { useMessageApi } from '@/component/context/messageContext/message'
import TableSelects, {
  SelectItem,
} from '@/component/common/tableSelects/tableSelects'
import _ from 'lodash'
import dayjs from 'dayjs'
import { MyForm, MyFormProps } from '@/component/common/myForm'
export default function ExamConf() {
  const location = useLocation()
  const [curExamData, setCurExamData] = useState<any>({
    name: '',
  })
  const [examUsers, setExamUsers] = useState<any[]>([])
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([])
  const [userSelectedRowKeys, setUserSelectedRowKeys] = useState<number[]>([])
  const messageApi = useMessageApi()
  const [userDialog, setUserDialog] = useState<boolean>(false)
  const [searchParams, setSearchParams] = useState({
    pageNum: 1,
    pageSize: 20,
    name: '',
    phone: '',
    email: '',
    auth: 'user',
  })
  const [testSearchParams, setTestSearchParams] = useState({
    name: '',
  })
  const [testData, setTestData] = useState<any[]>([])
  const [isShowCheatPanel, setIsShowCheatPanel] = useState<boolean>(false)
  const [isShowPaperConf, setIsShowPaperConf] = useState<boolean>(false)

  const getExam = (id: string) => {
    examApi.getExams({ id }).then((data: any) => {
      setCurExamData(data.exam)
      editForm.setFieldsValue({ ...data.exam })
      setExamPaperConfData(
        data.papers.map((item: any) => {
          return item.id
        })
      )
      PaperConfForm.setFieldsValue({
        exampapers: data.papers.map((item: any) => {
          return item.id
        }),
      })
      setExamUsers(data.users)
      const usedUserId = data.users.map((item: any) => {
        return item.id
      })
      setUserSelectedRowKeys(usedUserId)
      setTestData(data.tests)
    })
  }
  const [state, setState] = useState({
    isShowUserManage: false,
  })
  const [userData, setUserData] = useState<UserArr>({
    users: [],
    total: 0,
  })
  // 获取全部用户api
  const getUsers = (params: any) => {
    userApi.getUsers(params).then((res: any) => {
      res.users.forEach((element: any) => {
        element.key = element.id
      })
      setUserData(res)
    })
  }

  useEffect(() => {
    getExam(location.pathname.split('/')[4])
    getUsers(searchParams)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location.pathname])

  // 全部用户Dialog
  const UserDialog = () => {
    const addExamUsers = async (examId: string, userIds: Array<number>) => {
      await examApi.addExamUser({ examId, userIds }).then((res) => {
        messageApi.success('添加成功')
        getExam(location.pathname.split('/')[4])
        setUserDialog(false)
      })
    }

    // 用户列表
    const UserTable = () => {
      const rowSelection = {
        selectedRowKeys: userSelectedRowKeys,
        onChange: (selectedRowKeys: any) => {
          setUserSelectedRowKeys(selectedRowKeys)
        },
        getCheckboxProps: (record: any) => ({
          disabled: false,
        }),
      }
      const columns: any = [
        {
          title: '姓名',
          dataIndex: 'name',
          key: 'name',
          align: 'center',
        },
        {
          title: '性别',
          dataIndex: 'sex',
          key: 'sex',
          align: 'center',
          render: (_: any, { sex }: any) => <>{USER_SEX[sex - 1]?.label}</>,
        },
        {
          title: '手机号',
          dataIndex: 'phone',
          key: 'phone',
          align: 'center',
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          key: 'email',
          align: 'center',
        },
        {
          title: '出生日期',
          dataIndex: 'birth_day',
          key: 'birth_day',
          render: (text: string) => {
            return text?.slice(0, 10)
          },
          align: 'center',
        },
        {
          title: '户籍地区',
          dataIndex: 'home',
          key: 'home',
          align: 'center',
          render: (_: any, { home }: any) => (
            <RegionSelect onlyRead value={home}></RegionSelect>
          ),
        },
      ]
      return (
        <MyTable
          rowSelection={rowSelection}
          rowKey={(record) => record.id}
          dataSource={userData?.users}
          columns={columns}
          pageSize={searchParams.pageSize}
          total={userData.total}
          onPaginationChange={(pageNum, pageSize) => {
            setSearchParams((oldV) => {
              return {
                ...oldV,
                pageNum,
                pageSize,
              }
            })
          }}></MyTable>
      )
    }
    // 过滤器组件
    const UserFilter = () => {
      const tableOptions: SelectItem[] = [
        {
          render: (
            <Input
              key="name"
              placeholder="搜索姓名"
              value={searchParams.name}
              allowClear
              onChange={(e) => {
                setSearchParams((oldV) => {
                  return { ...oldV, name: e.target.value }
                })
              }}
            />
          ),
        },
        {
          render: (
            <Input
              key="phone"
              placeholder="搜索手机号"
              value={searchParams.phone}
              allowClear
              onChange={(e) => {
                setSearchParams((oldV) => {
                  return { ...oldV, phone: e.target.value }
                })
              }}
            />
          ),
        },
        {
          render: (
            <Input
              key="email"
              placeholder="搜索邮箱"
              value={searchParams.email}
              allowClear
              onChange={(e) => {
                setSearchParams((oldV) => {
                  return { ...oldV, email: e.target.value }
                })
              }}
            />
          ),
        },
      ]
      return (
        <TableSelects
          options={tableOptions}
          source={searchParams}
          onReset={() => {
            setSearchParams({
              pageNum: 1,
              pageSize: 20,
              name: '',
              phone: '',
              email: '',
              auth: 'user',
            })
            getUsers({
              pageNum: 1,
              pageSize: 20,
              name: '',
              phone: '',
              email: '',
              auth: 'user',
            })
          }}
          onSearch={() => {
            getUsers({
              pageNum: searchParams.pageNum,
              pageSize: searchParams.pageSize,
              name: searchParams.name,
              phone: searchParams.phone,
              email: searchParams.email,
              auth: 'user',
            })
          }}></TableSelects>
      )
    }
    return (
      <MyDialog
        width="80%"
        open={userDialog}
        onCancel={() => setUserDialog(false)}
        onClose={() => setUserDialog(false)}
        onOk={() => {
          addExamUsers(location.pathname.split('/')[4], userSelectedRowKeys)
        }}>
        <div style={{ height: '60vh' }}>
          {UserFilter()}
          {UserTable()}
        </div>
      </MyDialog>
    )
  }
  // 用户管理抽屉
  const UserDrawer = () => {
    const rowSelection = {
      onChange: (selectedRowKeys: any) => {
        setSelectedRowKeys(selectedRowKeys)
      },
      getCheckboxProps: (record: any) => ({
        disabled: false,
      }),
    }
    const userColumns = [
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '手机号',
        dataIndex: 'phone',
        key: 'phone',
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        key: 'email',
      },
    ]
    /**
     * 删除笔试用户
     * @param meetingId
     * @param userIds
     */
    const delExamUsers = async (examId: string, userIds: Array<number>) => {
      await examApi.delExamUsers({ examId, userIds }).then((res) => {
        messageApi.success('删除成功')
        getExam(location.pathname.split('/')[4])
      })
    }
    return (
      <MyDrawer
        open={state.isShowUserManage}
        footer={
          <Flex gap={'1rem'} justify="right">
            {selectedRowKeys.length > 0 && (
              <Button
                onClick={() => {
                  delExamUsers(location.pathname.split('/')[4], selectedRowKeys)
                }}>
                删除
              </Button>
            )}
            <Button onClick={() => setUserDialog(true)}>添加笔试者</Button>
            <Button
              htmlType="submit"
              onClick={() => {
                setState((oldV) => {
                  return { ...oldV, isShowUserManage: false }
                })
              }}>
              确定
            </Button>
          </Flex>
        }
        onClose={() => {
          setState((oldV) => {
            return { ...oldV, isShowUserManage: false }
          })
        }}>
        <MyTable
          page={false}
          rowSelection={rowSelection}
          rowKey={(record) => record.id}
          dataSource={examUsers}
          columns={userColumns}></MyTable>
        {UserDialog()}
      </MyDrawer>
    )
  }

  // 防作弊配置面板
  const [editForm] = Form.useForm()
  const CheatPanel = () => {
    const updateConfig = () => {
      examApi
        .updateConfig({
          examId: location.pathname.split('/')[4],
          ...editForm.getFieldsValue(),
        })
        .then((res) => {
          getExam(location.pathname.split('/')[4])
          messageApi.success('修改成功')
          setIsShowCheatPanel(false)
        })
    }
    const editCheatFormConf: MyFormProps = {
      name: 'editForm',
      form: editForm,
      conf: [
        {
          name: 'screen_recording',
          label: '屏幕录制',
          content: <Switch />,
        },
        {
          name: 'face_recording',
          label: '视频录制',
          content: <Switch />,
        },
        {
          name: 'is_limit_jump',
          label: '切屏限制',
          content: <Switch />,
        },
        {
          name: 'limit_jump_times',
          label: '限制次数',
          content: (
            <Input
              style={{ width: '50%' }}
              placeholder="请输入切屏次数"
              suffix="次"
            />
          ),
        },
      ],
      onValuesChange: (changedValues, allValues) => {
        setCurExamData((oldV: any) => {
          return {
            ...oldV,
            ...allValues,
          }
        })
      },
    }
    return (
      <MyDrawer
        forceRender
        width="20%"
        open={isShowCheatPanel}
        footer={
          <Flex gap={'1rem'} justify="right">
            <Button
              htmlType="submit"
              onClick={() => {
                updateConfig()
              }}>
              确定
            </Button>
          </Flex>
        }
        onClose={() => {
          setIsShowCheatPanel(false)
        }}>
        <Flex style={{ height: '100%' }} justify="center">
          <MyForm {...editCheatFormConf}></MyForm>
        </Flex>
      </MyDrawer>
    )
  }

  // 试卷配置面板
  const [examPaperData, setExamPaperData] = useState<any[]>([])
  const getPaperList = (params: any) => {
    paperApi.getPaperList(params).then((data: any) => {
      setExamPaperData(
        data.ques.map((item: any) => {
          return {
            value: item.id,
            label: item.name,
          }
        })
      )
    })
  }
  useEffect(() => {
    getPaperList({ pageNum: 1, pageSize: 999, name: '' })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const [PaperConfForm] = Form.useForm()
  const [examPaperConfData, setExamPaperConfData] = useState<any>({
    exampapers: [],
  })

  const PaperConfPanel = () => {
    const linkExamPaper = () => {
      examApi
        .linkExamPaper({
          examId: location.pathname.split('/')[4],
          testPaperIds: examPaperConfData.exampapers,
        })
        .then((res) => {
          getExam(location.pathname.split('/')[4])
          messageApi.success('修改成功')
          setIsShowPaperConf(false)
        })
    }
    const editPaperFormConf: MyFormProps = {
      name: 'PaperConfForm',
      form: PaperConfForm,
      conf: [
        {
          name: 'exampapers',
          label: '选择试卷',
          content: (
            <Select
              mode="multiple"
              allowClear
              placeholder="选择试卷"
              optionFilterProp="label"
              filterSort={(optionA, optionB) =>
                (optionA?.label ?? '')
                  .toLowerCase()
                  .localeCompare((optionB?.label ?? '').toLowerCase())
              }
              options={examPaperData}
            />
          ),
        },
      ],
      onValuesChange: (changedValues, allValues) => {
        setExamPaperConfData((oldV: any) => {
          return {
            ...oldV,
            ...allValues,
          }
        })
      },
    }
    return (
      <MyDrawer
        forceRender
        width="30%"
        open={isShowPaperConf}
        footer={
          <Flex gap={'1rem'} justify="right">
            <Button
              htmlType="submit"
              onClick={() => {
                linkExamPaper()
              }}>
              确定
            </Button>
          </Flex>
        }
        onClose={() => {
          setIsShowPaperConf(false)
        }}>
        <MyForm {...editPaperFormConf}></MyForm>
      </MyDrawer>
    )
  }

  // 笔试列表
  const TestList = () => {
    const sendEmail = async (id: string) => {
      await examApi
        .sendEmail({
          examId: location.pathname.split('/')[4],
          userId: id,
        })
        .then((res: any) => {
          if (res.type === 'success') {
            messageApi.success(res.msg)
          } else {
            messageApi.error(res.msg)
          }
        })
    }
    // 笔试列表
    const examTable = () => {
      const columns: any = [
        {
          title: '名称',
          dataIndex: 'name',
          key: 'name',
          align: 'center',
          render: (_: any, { name, sex }: any) => <>{name} 的笔试</>,
        },
        {
          title: '手机号',
          dataIndex: 'phone',
          key: 'phone',
          align: 'center',
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          key: 'email',
          align: 'center',
        },
        {
          title: '是否提交',
          dataIndex: 'is_submit',
          key: 'is_submit',
          align: 'center',
          render: (_: any, { is_submit }: any) => {
            return <Tag>{is_submit === 1 ? '已提交' : '未提交'}</Tag>
          },
        },
        {
          title: '是否作弊',
          dataIndex: 'is_dirty',
          key: 'is_dirty',
          align: 'center',
          render: (_: any, { is_dirty }: any) => {
            return (
              <Tag color={is_dirty === 1 ? 'red' : 'green'}>
                {is_dirty === 1 ? '疑似作弊' : '正常'}
              </Tag>
            )
          },
        },
        {
          title: '成绩',
          dataIndex: 'total_score',
          key: 'total_score',
          align: 'center',
          render: (_: any, { total_score }: any) => {
            return <>{total_score ? `${total_score}分` : '--'}</>
          },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          align: 'center',
          render: (
            _: any,
            { user_id, is_send_email, is_submit, judge_res }: any
          ) => {
            return (
              <Flex justify="space-around">
                {is_submit ? (
                  <Button
                    size="small"
                    variant="text"
                    onClick={() => {
                      setUserTest(JSON.parse(judge_res))
                      setTimeout(() => {
                        setIsShowUserTest(true)
                      }, 0);
                    }}>
                    查看成绩
                  </Button>
                ) : (
                  <Button
                    size="small"
                    variant="text"
                    onClick={() => {
                      sendEmail(user_id)
                    }}>
                    {is_send_email ? '再次发送' : '发送邮件'}
                  </Button>
                )}
              </Flex>
            )
          },
        },
      ]
      return (
        <MyTable
          rowKey={(record) => record.id}
          dataSource={testData}
          columns={columns}
          page={false}></MyTable>
      )
    }
    // 过滤器组件
    const examFilter = () => {
      const tableOptions: SelectItem[] = [
        {
          render: (
            <Input
              key="name"
              placeholder="搜索姓名"
              value={testSearchParams.name}
              allowClear
              onChange={(e) => {
                setTestSearchParams({ name: e.target.value })
              }}
            />
          ),
        },
      ]
      return (
        <TableSelects
          options={tableOptions}
          source={testSearchParams}
          onSearch={() => {
            const sortedUsers = _.orderBy(testData, [
              (user) => {
                return -_.indexOf(
                  user.name.toLowerCase(),
                  testSearchParams.name.toLowerCase()
                )
              },
            ])
            setTestData(sortedUsers)
          }}></TableSelects>
      )
    }

    return (
      <div className="interview-list">
        {examFilter()}
        {examTable()}
      </div>
    )
  }

  const [isShowUserTest, setIsShowUserTest] = useState(false)
  const [userTest, setUserTest] = useState<any>()
  const UserTestDrawer = () => {
    return (
      <MyDrawer
        forceRender
        width="50%"
        open={isShowUserTest}
        footer={
          <Flex gap={'1rem'} justify="right">
            <Button
              htmlType="submit"
              onClick={() => {
                setIsShowUserTest(false)
              }}
            />
          </Flex>
        }>
          
        </MyDrawer>
    )
  }

  return (
    <div className="meeting-conf">
      <Flex justify="space-between" className="meeting-title">
        <div style={{ width: '25%' }}></div>
        <Flex vertical>
          <h2>{curExamData?.name}</h2>
          <Flex className="time">
            {dayjs(curExamData.begin).format('YYYY-MM-DD HH:mm:ss')} ~{' '}
            {dayjs(curExamData.end).format('YYYY-MM-DD HH:mm:ss')}
            <span className="min">（{curExamData.duration}分钟）</span>
          </Flex>
        </Flex>
        <Flex style={{ width: '25%' }} justify="space-around">
          <Button
            onClick={() => {
              setState((oldV) => {
                return {
                  ...oldV,
                  isShowUserManage: true,
                }
              })
            }}>
            人员配置
          </Button>
          <Button
            onClick={() => {
              setIsShowPaperConf(true)
            }}>
            试卷配置
          </Button>
          <Button
            onClick={() => {
              editForm.setFieldsValue({ ...curExamData })
              setIsShowCheatPanel(true)
            }}>
            反作弊配置
          </Button>
        </Flex>
      </Flex>
      <Flex style={{ width: '100%', height: '100%' }}>
        <div className="meeting-content">{TestList()}</div>
      </Flex>
      {UserDrawer()}
      {CheatPanel()}
      {PaperConfPanel()}
      {UserTestDrawer()}
    </div>
  )
}
